package com.xdtech.wx.controller;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.common.utils.EmptyUtil;
import com.xdtech.common.utils.ExcelHelper;
import com.xdtech.core.model.BaseItem;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.web.controller.BaseController;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.wx.service.WxUserInfoService;
import com.xdtech.wx.vo.WxUserInfoItem;

/**
 * 
 * @author max.zheng
 * @create 2018-01-04 11:30:24
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class WxUserInfoController extends BaseController{
	@Autowired
	private WxUserInfoService wxUserInfoService;
	@RequestMapping(value="/wxUserInfo.do",params = "wxUserInfo")
	public ModelAndView skipWxUserInfo() {
		return new ModelAndView("wx/wxUserInfo/wxUserInfo_ftl");
	}
	
	@RequestMapping(value="/wxUserInfo.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(WxUserInfoItem item,Pagination pg) {
		Map<String, Object> results =  wxUserInfoService.loadPageDataByConditions(pg,item,"findWxUserInfoByCondition");
		return results;
	}
	
	@RequestMapping(value="/wxUserInfo.do",params = "editWxUserInfo")
	@SystemControllerLog(description = "编辑")
	public ModelAndView editWxUserInfo(HttpServletRequest request,Long wxUserInfoId) {
		if (wxUserInfoId!=null) {
			request.setAttribute("wxUserInfoItem", wxUserInfoService.loadWxUserInfoItem(wxUserInfoId));
		}
		return new ModelAndView("wx/wxUserInfo/editWxUserInfo_ftl");
	}
	
	@RequestMapping(value="/wxUserInfo.do",params = "saveWxUserInfo")
	@ResponseBody
	@SystemControllerLog(description = "保存")
	public ResultMessage saveWxUserInfo(WxUserInfoItem item) {
		ResultMessage r = new ResultMessage();
		if (wxUserInfoService.saveOrUpdateWxUserInfo(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/wxUserInfo.do",params = "deleteWxUserInfoItems")
	@ResponseBody
	@SystemControllerLog(description = "删除")
	public ResultMessage deleteWxUserInfoItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> wxUserInfoIds = new ArrayList<Long>();
			for (String id : tempIds) {
				wxUserInfoIds.add(Long.valueOf(id));
			}
			wxUserInfoService.deleteWxUserInfoInfo(wxUserInfoIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	@RequestMapping(value="/wxUserInfo.do",params = "resetWxUserInfoItems")
	@ResponseBody
	@SystemControllerLog(description = "重置签到信息")
	public ResultMessage resetWxUserInfoItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> wxUserInfoIds = new ArrayList<Long>();
			for (String id : tempIds) {
				wxUserInfoIds.add(Long.valueOf(id));
			}
			wxUserInfoService.resetWxUserInfoInfo(wxUserInfoIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/wxUserInfo.do",params = "importFile")
	public ModelAndView importFile(HttpServletRequest request, String actionUrl) {
		request.setAttribute("actionUrl", actionUrl);
		return new ModelAndView("common/editImportFile_ftl");
	}
	@RequestMapping(value="/wxUserInfo.do",params="export")
	public void export(HttpServletRequest request,HttpServletResponse response) {
		try
		{
			List<WxUserInfoItem> items = wxUserInfoService.loadItems();
			exportExcelData(new WxUserInfoItem(), response, items, "微信签到信息");
		}
		catch (Exception e)
		{
			log.error("导出微信签到信息异常", e);
		}
	}
	protected void exportExcelData(BaseItem condition, HttpServletResponse response,List<?> items,String title)
			throws Exception, FileNotFoundException, IOException {
		String fileName = condition.getClass().getSimpleName()+DateUtil.getDate(new Date(), DateStyle.YYYYMMDDHHMMSS)+".xls";
		String exportUrl = ApplicationContextUtil.getWebappUrl()+"template/";
		File exportFile = new File(ApplicationContextUtil.getWebappUrl()+"template");
		if (!exportFile.exists())
		{
			exportFile.mkdir();
		}
		String fileUrl = exportUrl+"/"+fileName;
		OutputStream out = new FileOutputStream(fileUrl);
//		ExcelHelper.exportByGrid(title,"20",condition.getClass(), items, out);
		ExcelHelper.exportByGrid(title,"20",condition.getClass(), items, out);

		out.flush();
		out.close();
		//读写设定好的excel模版
		InputStream fis = new BufferedInputStream(new FileInputStream(new File(fileUrl)));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();
		
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+fileName);
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
	}
	@RequestMapping(params = "import")
	@ResponseBody
	public ResultMessage importUser(
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
		try {
			if (EmptyUtil.isNotEmpty(myfiles)) {
				MultipartFile file = myfiles[0];
				if (file.getOriginalFilename().endsWith(".xls")||file.getOriginalFilename().endsWith(".xlsx")) {
					List<WxUserInfoItem> items = ExcelHelper.importExcel(file.getInputStream(), WxUserInfoItem.class);
					if (EmptyUtil.isEmpty(items)) {
						r.setFailMsg("导入数据为空");
					}else {
						wxUserInfoService.saveImportWxUserInfos(items);
					}
				} else {
					r.setFailMsg("文件格式不对，请导入正确Excel文件（xls格式）");
				}
			}else {
				r.setFailMsg("导入文件为空");
			}
			
		} catch (Exception e) {
			log.error("用户信息导入异常",e);
			r.setFailMsg("后台数据处理异常！");
		}
		
		return r;
	}

}
